package com.hsource.paymentcenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.hsource.common.utils.CommonResp;
import com.hsource.common.utils.resultUtils.controller.BaseController;
import com.hsource.paymentcenter.conf.wx.WXPay;
import com.hsource.paymentcenter.conf.wx.WXPayConfig;
import com.hsource.paymentcenter.conf.wx.WechatConfig;
import com.hsource.paymentcenter.domain.pay.Refund;
import com.hsource.paymentcenter.service.impl.AliPayServiceImpl;
import com.hsource.paymentcenter.util.StringUtils;
import com.hsource.paymentcenter.util.enums.PayServiceEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/10/10 13:52
 * @describe 支付控制层
 */
@Slf4j
@Controller
@RequestMapping("/pay")
public class PayController extends BaseController {

    @Autowired
    private WechatConfig config;

    /**
     * 退款接口
     * @param refund 退款接口
     * @return
     */
    @ResponseBody
    @RequestMapping("/refund")
    public CommonResp refund(@RequestBody String refundString){
        Refund refund = JSONObject.parseObject(refundString, Refund.class);
        Object o = openingServiceReverberate_PayRefund(refund);
        if(StringUtils.isNull(o)){
            return failed();
        }
        if((boolean)o){
            return success();
        }
        return failed();
    }

    /**
     * 支付通知回调
     * @param request 请求体
     * @param payType 支付类型
     * @return
     */
    @ResponseBody
    @RequestMapping("/payNotify/{payType}")
    public CommonResp payNotify(HttpServletRequest request,@PathVariable("payType")String payType) throws IOException {
        openingServiceReverberate_PayNotify(payType,request);
        return success();
    }

    /**
     * 统一下单接口
     * @param orderId 订单id
     * @param request 请求体
     * @param response 响应体
     * @param payType 支付类型
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/goPay")
    public CommonResp goPay(String orderId, HttpServletRequest request, HttpServletResponse response,String payType) throws Exception {
        Object objectString=openingServiceReverberate_Pay(payType,orderId,request);

        if(StringUtils.isNotNull(objectString)) {
            Map<String,Object> map=new HashMap<>();
            if(payType.equals("WECHAT")) {
                map.put("payPamars", JSONObject.parseObject(objectString.toString()));
            }
            if(payType.equals("ALIPAY")){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("sign",objectString.toString());
                map.put("payPamars",jsonObject);
            }
            return success(map);
        }else{
            return failed();
        }
    }
    /**
     * 根据支付类型调取支付退款
     * @param refund 退款对象参数
     */
    public static Object openingServiceReverberate_PayRefund(Refund refund){
        try {
            Class<?> clazz = Class.forName("com.hsource.paymentcenter.service.impl." + PayServiceEnum.getServiceImpl(refund.getPay_type().toUpperCase()+"_REFUND"));
            Method openingService = clazz.getMethod("refund",Refund.class);
            Object invoke = openingService.invoke(clazz.newInstance(), refund);
            return invoke;
        }catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据支付类型调取支付通知回调
     * @param payType 支付类型
     * @param request 请求体
     */
    public static void openingServiceReverberate_PayNotify(String payType,HttpServletRequest request){
        try {
            Class<?> clazz = Class.forName("com.hsource.paymentcenter.service.impl." + PayServiceEnum.getServiceImpl(payType.toUpperCase()+"_NOTIFY"));
            Method openingService = clazz.getMethod("payNotify", String.class,HttpServletRequest.class);
            Object invoke = openingService.invoke(clazz.newInstance(), payType, request);
        }catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据支付类型调取支付服务
     * @param payType 支付类型
     * @param orderId 订单id
     * @param request 请求体
     *
     * @return 返回方法参数
     */
    public static Object openingServiceReverberate_Pay(String payType,String orderId,HttpServletRequest request){
        try {
            Class<?> clazz = Class.forName("com.hsource.paymentcenter.service.impl." + PayServiceEnum.getServiceImpl(payType.toUpperCase()));
            Method openingService = clazz.getMethod("toOrderPay", String.class,HttpServletRequest.class);
            Object invoke = openingService.invoke(clazz.newInstance(), orderId, request);
            return invoke;
        }catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            log.error(" 订单{"+orderId+"}-{"+payType+"}支付失败");
        }
        return null;
    }


}
